//题目链接：https://leetcode.cn/problems/kth-largest-element-in-an-array/

class Solution
{
public:
    int findKthLargest(vector<int> &nums, int k)
    {
        // 使用快速排序划分区间
        srand(time(NULL)); // 随机数种子
        return qsort(nums, 0, nums.size() - 1, k);
    }
    int qsort(vector<int> &nums, int begin, int end, int k)
    {
        if (begin == end)
            return nums[begin];
        // 1. 快速排序划分区间
        int key = getRandom(nums, begin, end);
        int left = begin - 1, right = end + 1, i = begin;
        while (i < right)
        {
            if (nums[i] < key)
                swap(nums[++left], nums[i++]);
            else if (nums[i] == key)
                ++i;
            else
                swap(nums[--right], nums[i]);
        }
        // 2.
        int b = right - left - 1, c = end - right + 1;
        if (c >= k)
            return qsort(nums, right, end, k);
        else if (b + c >= k)
            return key;
        else
            return qsort(nums, begin, left, k - b - c);
    }
    int getRandom(vector<int> &nums, int begin, int end)
    {
        int tmp = rand();
        return nums[tmp % (end - begin + 1) + begin];
    }
};